Programming Language:
    Start Up | Variables & Loops | Functions | Arrays | File I/O

    DECLARATION OF VARIABLES AND SIMPLE LOOPS

    - first programing steps with Xi -

    The following program lines serve to compute the factorial n!=1*...*n. First you have to declare a variable in order to store the result. These are the six possible types of numerical values:

    Type Memory Size Range Manner
    char 1Byte 0..255 integer
    short 2Byte -32767..32768 integer
    int 4Byte -2147483647..2147483648 integer
    float 4Byte depends on architecture floating point
    double 8Byte depends on architecture floating point
    complex 16Byte depends on architecture complex floating point

    In our case you could take int:

    (  1)>int n=1;
    
    For evaluating the factorial you will have to program a for-loop. Xi uses the same syntax as C does:
    (  2)>for (i=1; i<=10; i++) n*=i;
    
    This computes 10!=3628800. To print out the result use the C-like printf-statement:
    (  3)>printf("10!=%d\n",n);
    10!=3628800
    

    The variable i in the for-loop isn't declared explicitly. This points out the main difference to C. In Xi it isn't necessary to declare all variables. If you use a variable without declaring the interpreter the programm makes assumptions about the type. In this example the interpreter recognizes that i should be an int. You can get the type of a variable with the rather 'quick and dirty' print-command:

    (  4)>print(i);
    <int> 11
    
    The Interpreter will change the type of an undeclared variable if needed.
    (  5)>i=i*1.3
    (  6)>print(i);
    <double> 14.3
    
    Nevertheless the interpreter won't change the types of explicit declared variables.
    (  7)>int j=0;
    (  8)>j=j*1.3;
    (  9)>print(j);
    <int> 0
    
    The next short example determines the factorial by using a while-loop.
    ( 10)>int i=1, n=1;
    ( 11)>while (i<=10) { n*=i; i++;}
    
    Another possibility is:
    ( 12)>int k=1, l=1;
    ( 13)>while ((k++) <=9) l*=k;
    
    and all dirty combinations of pre- and postfix, decrement or increment operators.


    Rechts Index Index Index Linls © 1995 by Bodo Junglas, Klaus Spanderen and Fabian Weis
    - Last revised: April 23 1996